package com.linuxrm.countdown.gaokao
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.view.Choreographer
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import android.window.OnBackInvokedCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import android.util.Log
import java.io.File
import java.io.IOException
class MainActivity : AppCompatActivity() {
    private lateinit var gaokaoDate: Calendar
    private lateinit var tvDateTime: TextView
    private lateinit var tvCountdown: TextView
    private lateinit var frameCallback: Choreographer.FrameCallback
    private lateinit var rootContainer: View
    private lateinit var contentContainer: View
    private lateinit var btnSettings: Button
    private lateinit var backCallback: OnBackInvokedCallback
    private val moveHandler = Handler(Looper.getMainLooper())
    private val moveRunnable = object : Runnable {
        override fun run() {
            randomMoveContainer()
            moveSettingsButton()
            moveHandler.postDelayed(this, 30000)
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        rootContainer = findViewById(R.id.root_container)
        btnSettings = findViewById(R.id.btn_settings)
        contentContainer = findViewById(R.id.content_container)
        contentContainer.scaleX = 0.75f
        contentContainer.scaleY = 0.75f
        tvDateTime = findViewById(R.id.tv_current_datetime)
        tvCountdown = findViewById(R.id.tv_countdown)
        loadTargetDateTime()
        btnSettings.setOnClickListener {
            showDateTimePicker()
        }
        frameCallback = object : Choreographer.FrameCallback {
            override fun doFrame(frameTimeNanos: Long) {
                updateDisplay()
                Choreographer.getInstance().postFrameCallback(this)
            }
        }
        rootContainer.post {
            randomMoveContainer()
            moveSettingsButton()
        }
        refreshWidget()
        initDaemonProcess()
    }
    override fun onDestroy() {
        super.onDestroy()
        Choreographer.getInstance().removeFrameCallback(frameCallback)
        moveHandler.removeCallbacksAndMessages(null)
    }
    private fun updateDaemonStatus() {
        val isRunning = CountdownLogic.isDaemonRunning(this)
        val tvRoot = findViewById<TextView>(R.id.tv_root)
        tvRoot.visibility = if (isRunning) View.GONE else View.VISIBLE
    }
    override fun onResume() {
        super.onResume()
        Choreographer.getInstance().postFrameCallback(frameCallback)
        moveHandler.post(moveRunnable)
    }
    override fun onPause() {
        super.onPause()
        Choreographer.getInstance().removeFrameCallback(frameCallback)
        moveHandler.removeCallbacks(moveRunnable)
    }
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (::rootContainer.isInitialized) {
            rootContainer.post {
                randomMoveContainer()
                moveSettingsButton()
            }
        }
        refreshWidget()
    }
    private fun initDaemonProcess() {
        Thread {
            try {
                val scriptFile = File(filesDir, "widget_daemon.sh")
                if (!scriptFile.exists()) {
                    val scriptContent = assets.open("widget_daemon.sh").bufferedReader().use { it.readText() }
                    scriptFile.writeText(scriptContent)
                    Runtime.getRuntime().exec(arrayOf("chmod", "700", scriptFile.absolutePath)).waitFor()
                }
                Runtime.getRuntime().exec(arrayOf("su", "-c", "sh", scriptFile.absolutePath))
            } catch (e: Exception) {
                Log.e("DAEMON", "守护进程初始化失败", e)
            }
        }.start()
        runOnUiThread { updateDaemonStatus() }
    }
    private fun randomMoveContainer() {
        if (rootContainer.width == 0 || rootContainer.height == 0) return
        val maxOffsetX = (rootContainer.width * 0.1).toInt()
        val maxOffsetY = (rootContainer.height * 0.1).toInt()
        val randomX = (-maxOffsetX..maxOffsetX).random()
        val randomY = (-maxOffsetY..maxOffsetY).random()
        val params = contentContainer.layoutParams as FrameLayout.LayoutParams
        params.setMargins(randomX, randomY, 0, 0)
        contentContainer.layoutParams = params
    }
    private fun moveSettingsButton() {
        if (rootContainer.width == 0 || rootContainer.height == 0) return
        val maxOffsetX = (rootContainer.width * 0.2).toInt()
        val maxOffsetY = (rootContainer.height * 0.05).toInt()
        val offsetX = (0..maxOffsetX).random()
        val offsetY = (0..maxOffsetY).random()
        val params = btnSettings.layoutParams as FrameLayout.LayoutParams
        params.setMargins(0, offsetY, offsetX, 0)
        btnSettings.layoutParams = params
    }
    private fun loadTargetDateTime() {
        gaokaoDate = CountdownLogic.getTargetDate(this)
    }
    private fun saveTargetDateTime(calendar: Calendar) {
        val prefs = getSharedPreferences("MainActivity", MODE_PRIVATE)
        with(prefs.edit()) {
            putLong(CountdownLogic.PREFS_KEY, calendar.timeInMillis)
            apply()
        }
        gaokaoDate = calendar
        refreshWidget()
    }
    private fun resetToDefaultDateTime() {
        val defaultDate = Calendar.getInstance().apply {
            set(Calendar.getInstance().get(Calendar.YEAR), Calendar.JUNE, 7, 9, 0, 0)
        }
        saveTargetDateTime(defaultDate)
        updateDisplay()
        showToast("已重置为默认日期")
    }
    private fun showDateTimePicker() {
        val datePicker = DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                val timePicker = TimePickerDialog(
                    this,
                    { _, hourOfDay, minute ->
                        confirmDateTime(year, month, dayOfMonth, hourOfDay, minute)
                    },
                    gaokaoDate.get(Calendar.HOUR_OF_DAY),
                    gaokaoDate.get(Calendar.MINUTE),
                    true
                )
                timePicker.setTitle("选择时间")
                timePicker.show()
            },
            gaokaoDate.get(Calendar.YEAR),
            gaokaoDate.get(Calendar.MONTH),
            gaokaoDate.get(Calendar.DAY_OF_MONTH)
        )
        datePicker.setTitle("选择日期")
        datePicker.show()
    }
    private fun confirmDateTime(year: Int, month: Int, day: Int, hour: Int, minute: Int) {
        val selectedDate = Calendar.getInstance().apply {
            set(year, month, day, hour, minute, 0)
        }
        val formattedDate = CountdownLogic.dateFormat.format(selectedDate.time)
        AlertDialog.Builder(this)
            .setTitle("确认目标日期")
            .setMessage("您选择的目标日期时间为:\n$formattedDate")
            .setPositiveButton("确定") { _, _ ->
                saveTargetDateTime(selectedDate)
                showToast("目标日期已更新")
            }
            .setNegativeButton("取消", null)
            .setNeutralButton("重置为默认") { _, _ ->
                resetToDefaultDateTime()
            }
            .show()
    }
    private fun showToast(message: String) {
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
    }
    private fun updateDisplay() {
        tvDateTime.text = CountdownLogic.dateFormat.format(Date())
        tvCountdown.text = CountdownLogic.getCountdownText(gaokaoDate)
    }
    private fun refreshWidget() {
        startActivity(Intent(this, HiddenStarterActivity::class.java))
    }
}
